package cn.edu.cqupt.handler;

import cn.edu.cqupt.exception.ThrowingException;
import cn.edu.cqupt.until.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Andrew
 * @date 2018/1/9
 */
public class ThrowingExceptionHandler implements HandlerExceptionResolver {
    private final Logger logger = LoggerFactory.getLogger(ThrowingExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
        Result<Object> result = null;
        if (ex instanceof ThrowingException){
            ThrowingException ex1 = (ThrowingException) ex;
            result = Result.failed(ex1.getErrorCode(), ex1.getMessage());
            logger.debug("This is a ThrowingException: ",ex);
        }else if (ex instanceof NullPointerException){
            result = Result.failed("200","参数错误，数据异常！");
            logger.warn("This is a unknown exception: ",ex);
        }else {
            result = Result.failed("500","未知错误，请稍后再试！");
            logger.warn("This is a unknown exception: ",ex);
        }

        try {
            response.setHeader("content-type", "text/html;charset=UTF-8");
            response.getWriter().write(result.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
